import { defineStore } from 'pinia'
import userApi from '@/api/userApi'

export const useUserStore = defineStore('user', {
  state: () => ({
    accessToken: uni.getStorageSync('accessToken') || '',
    refreshToken: uni.getStorageSync('refreshToken') || '',
    userInfo: uni.getStorageSync('userInfo') || null
  }),
  
  getters: {
    isLogin: (state) => !!state.accessToken,
    avatar: (state) => state.userInfo?.avatar || '/static/default-avatar.png',
    nickname: (state) => state.userInfo?.nickname || '未登录'
  },
  
  actions: {
    // 登录
    login(accessToken, refreshToken, userInfo) {
      this.accessToken = accessToken
      this.refreshToken = refreshToken
      this.userInfo = userInfo
      uni.setStorageSync('accessToken', accessToken)
      uni.setStorageSync('refreshToken', refreshToken)
      uni.setStorageSync('userInfo', userInfo)
    },

    // 更新token
    updateToken(accessToken, refreshToken) {
      this.accessToken = accessToken
      this.refreshToken = refreshToken
      uni.setStorageSync('accessToken', accessToken)
      uni.setStorageSync('refreshToken', refreshToken)
    },
    
    // 登出
    logout() {
      this.accessToken = ''
      this.refreshToken = ''
      this.userInfo = null
      uni.removeStorageSync('accessToken')
      uni.removeStorageSync('refreshToken')
      uni.removeStorageSync('userInfo')
    },
    
    // 更新用户信息
    updateUserInfo(userInfo) {
      this.userInfo = userInfo
      uni.setStorageSync('userInfo', userInfo)
    },
    
    // 获取用户信息
    async fetchUserInfo() {
      try {
        const data = await userApi.getUserInfo()
        this.updateUserInfo(data)
        return data
      } catch (err) {
        this.logout()
        throw err
      }
    },
    
    // 更新头像
    async updateAvatar(avatar) {
      const newInfo = { ...this.userInfo, avatar }
      this.updateUserInfo(newInfo)
    }
  }
})
